/*
 * Copyright 2011 David de Mingo
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.shalma.internal;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

import org.shalma.Activator;
import org.shalma.model.Entity;
import org.shalma.model.Property;

@XmlRootElement(name = "module")
public class Module {

	private transient URL url;

	private transient Activator activator;

	private transient List<Class<? extends Entity>> entities;

	private transient List<Class<? extends Property<?>>> properties;

	@XmlElement(name = "activator")
	private String $activator;

	@XmlElementWrapper(name = "entities")
	@XmlElement(name = "entity")
	private List<String> $entities;

	@XmlElementWrapper(name = "properties")
	@XmlElement(name = "property")
	private List<String> $properties;

	public Activator getActivator() {
		return activator;
	}

	public URL getURL() {
		return url;
	}

	public List<Class<? extends Entity>> getEntities() {
		return entities;
	}

	public List<Class<? extends Property<?>>> getProperties() {
		return properties;
	}

	@SuppressWarnings("unchecked")
	void update(URL url) throws InstantiationException, IllegalAccessException,
			ClassNotFoundException {

		this.url = url;

		if ($activator != null)
			activator = (Activator) Class.forName($activator).newInstance();

		if ($entities == null)
			entities = Collections.emptyList();
		else {
			entities = new ArrayList<Class<? extends Entity>>();
			for (String entityName : $entities)
				entities.add((Class<? extends Entity>) ((Class<?>) Class
						.forName(entityName.trim())));
		}

		if ($properties == null)
			properties = Collections.emptyList();
		else {
			properties = new ArrayList<Class<? extends Property<?>>>();
			for (String propertyName : $properties)
				properties.add((Class<? extends Property<?>>) Class
						.forName(propertyName.trim()));
		}
	}
}
